<template>
  <div class="app-container">
    <el-drawer
      :title="title"
      :visible.sync="visible"
      size="80%"
      :before-close="cancel"
      custom-class="demo-drawer"
      :append-to-body="true"
    >
      <div class="demo-drawer__content dialogContent" style="padding: 20px;">
        <div style="margin-left: 20px;">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >导出
          </el-button>
        </div>
        <el-form ref="form" :model="form" label-width="auto">
          <el-row>
            <el-col :span="6">
              <el-form-item label="物料编码:" prop="itemCode">
                <el-input v-model="form.itemCode" placeholder disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料名称:" prop="itemName">
                <el-input v-model="form.itemName" placeholder disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="规格型号:" prop="specification">
                <el-input v-model="form.specification" placeholder disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="送检单号:" prop="iqcCode">
                <el-input v-model="form.iqcCode" placeholder disabled/>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="供应商:" prop="vendorName">
                <el-input v-model="form.vendorName" placeholder disabled/>
              </el-form-item>
            </el-col> -->
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="送检数量:" prop="quantityCheck">
                <el-input v-model="form.quantityCheck" placeholder disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="送检单号:" prop="iqcCode">
                <el-input v-model="form.iqcCode" placeholder disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检验时间:" prop="inspectDate">
                <el-input v-model="form.inspectDate" placeholder disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="抽样数量" prop="quantitySpotCheck">
                <el-input-number :controls="false" v-model="form.quantitySpotCheck" disabled/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="合格数量:" prop="receiveQty">
                <el-input v-model="form.receiveQty" placeholder disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="不合格数量:" prop="quantityUnqualified">
                <el-input v-model="form.quantityUnqualified" placeholder disabled/>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 中间的table -->
          <el-row>
            <el-table v-loading="loading1" :data="templateList" :span-method="objectSpanMethod">
              <!-- <el-table-column type="index" label="序号" width="50" :index="indexMethod"></el-table-column> -->
              <el-table-column label="检查项目" align="center" prop="inspectionItem" width="120px"/>
              <el-table-column label="缺陷等级" align="center" prop="defectLevel">
                <template
                  slot-scope="scope"
                >{{ scope.row.defectLevel == '1' ? 'A' : scope.row.defectLevel == '2' ? 'B' : 'C' }}
                </template>
              </el-table-column>
              <el-table-column
                label="检验标准及检验方法"
                align="center"
                prop="inspectionStandard"
                width="260px"
              />
              <el-table-column
                label="检验方式及工具"
                align="center"
                prop="inspectionMethod"
                width="140px"
              />
              <el-table-column label="抽样标准" align="center" prop="samplingStandards" width="140px"/>
              <el-table-column label="判定" align="center" prop="checkResult" width="140px">
                <template slot-scope="scope">
                  <div class="headerDiv">
                    <span>Ac={{ scope.row.acceptQty }},</span>
                    <span>Re={{ scope.row.rejectQty }}</span>
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="参考图片" align="center" prop="referenceImage" width="260px" /> -->
              <el-table-column label="检验记录" align="center" prop="analysisMethod" width="260px">
                <template slot-scope="scope">
                  <div class="headerDiv" v-if="scope.row.analysisMethod=='1'">
                    <!-- {{ scope.row.analysisMethod == "1"?"有比较值":"/"}} -->
                    <div>目标值:{{ scope.row.targetVal }}</div>
                    <!-- <div>比较符{{ scope.row.compareSymbol }}</div> -->
                    <div>
                      <span>上偏差:{{ scope.row.upOffset }}</span>
                      <span>下偏差:{{ scope.row.downOffset }}</span>
                    </div>
                    <div>
                      <span>上限差:{{ scope.row.upLimit }}</span>
                      <span>下限值:{{ scope.row.downLimit }}</span>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column align="center" prop="recordArray" width="140px" label="检验结果">
                <template slot-scope="scope">
                  <div v-if="scope.row.analysisMethod == '1'">
                    <!-- 实际值{{ scope.row.recordArray[0].actualValue }} -->
                    实际值:{{ scope.row.actualValue }}
                  </div>
                  <div
                    style="font-size:20px"
                  >{{ scope.row.checkResult == '0' ? '×' : scope.row.checkResult == '1' ? '√' : '--' }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-row>

          <el-form-item label="检验结果" prop="checkResult">
            <el-radio-group v-model="form.checkResult" disabled>
              <el-radio :label="1" value="1">√</el-radio>
              <el-radio :label="0" value="0">×</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注:" prop="remark">
                <el-input
                  :autosize="{ minRows: 2, maxRows: 5 }" 
                  style="width: 450px; height: 100px" 
                  type="textarea"
                  v-model="form.remark"
                  placeholder="输入备注"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <div v-if="form.checkResult == 0">
            <el-form-item label="不合格处理方式" prop="disposeType">
              <el-radio-group v-model="form.disposeType" disabled>
                <el-radio :label="0">返工/返修</el-radio>
                <el-radio :label="1">挑选</el-radio>
                <el-radio :label="2">让步</el-radio>
                <el-radio :label="3">退货</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="检验记录">
              <el-table :data="exceptionLogList">
                <el-table-column label="类型选择" align="center" prop="indexType">
                  <template slot-scope="scope">
                    <!-- <el-input v-model="scope.row.indexType" placeholder type="textarea" disabled /> -->
                    {{ scope.row.indexType }}
                  </template>
                </el-table-column>

                <el-table-column label="异常描述" align="center" prop="describeData"></el-table-column>
                <el-table-column label="文件上传" align="center" prop="checkResult">
                  <template slot-scope="scope">
                    <!-- <img :src="scope.row.fileName" alt /> -->
                    <!-- <el-image
                      style="width: 100px; height: 100px"
                      :src="scope.row.fileName"
                      :preview-src-list="[Array.from(scope.row.fileName)]"
                    ></el-image> -->
                    <ImageUpload
                      :limit="1"
                      :value="scope.row.fileName"
                      :fileSize="15"
                      @input="(url)=>handleImgUplaoded(url,scope.$index)"
                      @onRemoved="(url)=>handleImgRemoved(url,scope.$index)"
                    ></ImageUpload>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="medium"
                      type="text"
                      icon="el-icon-circle-plus-outline"
                      @click="errorAdd(item,i)"
                    ></el-button>
                    <el-button
                      v-if="scope.$index != 0"
                      size="medium"
                      type="text"
                      icon="el-icon-remove-outline"
                      @click="errorDel(scope.$index,i)"
                    ></el-button>
                  </template>
                </el-table-column>-->
              </el-table>
            </el-form-item>
          </div>
        </el-form>
        <div class="demo-drawer__footer" style="text-align: right;">
          <el-button type="primary" @click="cancel" v-if="optType =='view'">返回</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getDetail, exportIqcInfo } from '@/api/mes/qc/iqc'
import { tansParams, blobValidate } from '@/utils/hici'
import { Message, Loading } from 'element-ui'
import { saveAs } from 'file-saver'

let downloadLoadingInstance
export default {
  name: 'Iqc_detail',
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      title: '检验详情',
      visible: false,
      form: {},
      optType: undefined,
      // 模板列表
      templateList: [],
      loading1: false,
      // 不合格数
      failedSncode: [],
      // 序列码集合
      snObj: {},
      exceptionLogList: []
    }
  },
  created() {
  },
  methods: {
    init(isEdit, row) {
      //this.form = { ...row };
      console.log('详情页面', row)
      this.visible = true
      //调接口查询数据
      getDetail(row).then(res => {
        this.form = { ...res.data }
        console.log(this.form, '详情res')
        this.templateList = this.form.qcIqcInspectionItemList
        //给序列号赋值
        this.exceptionLogList = this.form.failedSncode[0].exceptionLogList
        //不合格处理方式的值转成number类型
        console.log(this.exceptionLogList, '=====this.exceptionLogList======')
        this.getSpanArr(this.form.qcIqcInspectionItemList)
      })
    },
    submitForm() {
    },
    // 取消按钮
    cancel() {
      this.visible = false
      this.reset()
    },
    //图片上传成功
    handleImgUplaoded(imgUrl) {
      console.log(imgUrl)
      this.form.sopUrl = imgUrl
    },
    //图片移除
    handleImgRemoved(imgUrl) {
      console.log(imgUrl)
      this.form.sopUrl = null
    },
    // 异常记录增加
    errorAdd(item, i) {
      let obj = {}
      this.failedSncode[i].exceptionLogList.push(obj)
    },
    // 删除异常记录
    errorDel(index, i) {
      this.failedSncode[i].exceptionLogList.splice(index, 1)
    },
    // 表单重置
    reset() {
      this.form = {
        iqcId: null,
        iqcCode: null,
        iqcName: null,
        templateId: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        vendorBatch: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityMinCheck: null,
        quantityMaxUnqualified: null,
        quantityRecived: null,
        quantityCheck: null,
        quantityUnqualified: null,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantity: null,
        majQuantity: null,
        minQuantity: null,
        checkResult: null,
        reciveDate: null,
        inspectDate: null,
        inspector: null,
        status: 'PREPARE',
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.autoGenFlag = false
      this.resetForm('form')
    },
    /** 导出按钮操作 */
    handleExport() {
      let query = { ...this.form };
      downloadLoadingInstance = Loading.service({
        text: "正在下载数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      // exportIqcInfo(query).then(res => {
      //     console.log(res, "======");
      //     downloadLoadingInstance.close();
      //   })
      exportIqcInfo(query).then(async data => {
          console.log(query, "======");
          const isBlob = blobValidate(data);
          if (isBlob) {
            const blob = new Blob([data]);
            saveAs(blob, query.iqcCode+`.xlsx`);
          } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
            Message.error(errMsg);
          }
          downloadLoadingInstance.close();
        }).catch(r => {
          console.error(r);
          Message.error("下载文件出现错误，请联系管理员！");
          downloadLoadingInstance.close();
        });
      // this.downloadDetail(
      //   "mes/qc/iqc/export/iqcInfo",
      //   {
      //     ...this.form
      //   },
      //   `iqcDetail_${new Date().getTime()}.xlsx`
      // );
    },
        // 行合并
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      console.log(rowIndex, "=====rowIndex======");
      if (columnIndex !== 6 && columnIndex !== 7) {
        const _row = this.spanArr1[rowIndex]; // 合并行数
        const _col = this.spanArr1[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col
        };
      }
      // if ( columnIndex !== 7) {
      //   const _row = this.spanArr1[rowIndex]; // 合并行数
      //   const _col = this.spanArr1[rowIndex] > 0 ? 1 : 0; // 合并的列数
      //   return {
      //     rowspan: _row,
      //     colspan: _col
      //   };
      // }
    },
    // 按照类型合并
    getSpanArr(data) {
      this.spanArr1 = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          // 当为第一行时
          if (i === 0) {
            this.spanArr1.push(1);
            this.pos = 0;
          } else {
            // 判断当前值是否与上一行的【名称】相等，相等则进行合并
            console.log(i, "=======i++====");
            if (data[i].inspectionStandard === data[i - 1].inspectionStandard  && data[i].inspectionItem === data[i - 1].inspectionItem) {
              this.spanArr1[this.pos] += 1; // 合并单元格：合并的行数 +1
              this.spanArr1.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
            } else {
              this.spanArr1.push(1); // 1代表当前这行的数据需要被显示
              this.pos = i;
              console.log(this.spanArr1, "======");
            }
          }
        }
        console.log(this.spanArr1, "=====spanArr1=======");
      }
    },
  }
}
</script>

<style lang="css">
.el-input-number.is-without-controls .el-input__inner {
  width: 130px;
  line-height: 30px;
  height: 35px;
}
</style>
